package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.remote.InvokeUserController;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.exceptions.SendCodeException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private InvokeUserController controller;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    /**
     * 登录
     */
    @Override
    public JwtResponse login(User user) {
        // 调用
        Result<User> userResult = controller.QueryByUserName(user.getUserName());
        User data = userResult.getData();
        // 用户名判断
        if (null == data){
            throw new SendCodeException("用户名错误");
        }
        // 密码
        if (!data.getUserPwd().equals(user.getUserPwd())){
            throw new SendCodeException("密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,
                JSONObject.toJSONString(data),TokenConstants.EXPIRATION, TimeUnit.MINUTES);

        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExistTime("15MIN");
        return jwtResponse;
    }

    /**
     * 获取个人信息
     * @return
     */
    @Override
    public User userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJSONOBrt = (String) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userJSONOBrt,User.class);
    }
    /**
     * 退出
     */
    @Override
    public void userLogout() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
